/*
 * Galaxium Messenger
 *
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

using G=Gtk;
using Gtk;
using Gdk;

using Anculus.Core;

namespace Galaxium.Gui.GtkGui
{
	public class InputTextField : TextView
	{
		public event EventHandler<SubmitTextEventArgs> TextSubmitted;
		
		private static G.TargetEntry[] TargetTable =
			new G.TargetEntry [] {
				new G.TargetEntry ("text/uri-list", 0, 0)
			};

		protected int _inputHistorySize;
		protected int _currentHistoryItem;
		protected List<string> _inputHistory;
		
		//TODO: get history size from the preferences
		public InputTextField ()
		{
			_inputHistorySize = 20;
			_inputHistory = new List<string> ();

			this.KeyPressEvent += new KeyPressEventHandler (KeyPressed);
			
			G.Drag.DestSet (this, DestDefaults.All, TargetTable, DragAction.Copy);
			DragDataReceived += DataReceived;
		}
		
		private void DataReceived (object sender, DragDataReceivedArgs args)
		{
			bool success = false;
			string data = System.Text.Encoding.UTF8.GetString (args.SelectionData.Data);
			
			switch (args.Info)
			{
				case 0: // text/uri-list
					string[] uriList = Regex.Split (data, "\r\n"); 
					
					foreach (string uri in uriList)
					{
						if (uri.Length > 0)
						{
							Log.Debug ("Dropped URI: "+uri);
						}
					}
					
					success = true;
					break;
			}
			
			G.Drag.Finish (args.Context, success, false, args.Time);
		}
		
		protected override bool OnKeyPressEvent (EventKey evnt)
		{
			base.OnKeyPressEvent (evnt);
			return false;
		}

		protected override bool OnKeyReleaseEvent (EventKey evnt)
		{
			base.OnKeyReleaseEvent (evnt);
			return false;
		}
		
		protected virtual void KeyPressed (object sender, KeyPressEventArgs args)
		{
			EventKey evnt = args.Event;
			
			if ((evnt.State & Gdk.ModifierType.ControlMask) == Gdk.ModifierType.ControlMask) {
				if (evnt.Key == Gdk.Key.Return || evnt.Key == Gdk.Key.KP_Enter)//ctrl-return
					AppendNewline ();
				args.RetVal = true;
			} else if (evnt.Key == Gdk.Key.Up) {
				if (_inputHistory.Count == 0) {
					args.RetVal = true;
					return;
				}
				
				if (_currentHistoryItem > 0) {
					_currentHistoryItem--;
					Buffer.Text = _inputHistory[_currentHistoryItem];
				}
				
				args.RetVal = true;
			} else if (evnt.Key == Gdk.Key.Down) {
				if (_inputHistory.Count == 0) {
					args.RetVal = true;
					return;
				}
				
				if (_currentHistoryItem < (_inputHistory.Count - 1)) {
					_currentHistoryItem++;
					Buffer.Text = _inputHistory[_currentHistoryItem];
				} else if (_currentHistoryItem == (_inputHistory.Count - 1)) {
					_currentHistoryItem++;
					Buffer.Text = String.Empty;
				}
				
				args.RetVal = true;
			} else if (evnt.Key == Gdk.Key.Return || evnt.Key == Gdk.Key.KP_Enter) {
				string text = Buffer.Text;
				Buffer.Clear ();

				//remove the newline at the end of the text
				text = text.Substring (0, text.Length - Environment.NewLine.Length);
				
				if (text.Length == 0) {
					args.RetVal = true;
					return;
				}
				
				AddInputHistory (text);
				OnTextSubmitted (new SubmitTextEventArgs (text));
			}
		}
		
		protected virtual void AddInputHistory (string line)
		{
			if (_inputHistory.Count == _inputHistorySize)
				_inputHistory.RemoveAt (0);
			
			_inputHistory.Add(line);
			_currentHistoryItem = _inputHistory.Count;
		}
		
		public virtual void AppendNewline ()
		{
			TextIter iter = Buffer.EndIter;
			Buffer.Insert (ref iter, Environment.NewLine);
		}
		
		public virtual void AppendText (string text)
		{
			TextIter iter = Buffer.EndIter;
			Buffer.Insert (ref iter, text);
		}
		
		protected virtual void OnTextSubmitted (SubmitTextEventArgs args)
		{
			if (TextSubmitted != null)
				TextSubmitted (this, args);
		}
	}
}